package com.ruoci.redis.specialcontroller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author yanglingjun
 *
 */
@Slf4j
@RestController
public class GeospatialController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/add")
    public void add(){
        redisTemplate.opsForGeo().add("home", new Point(117.485,30.648), "阿忠");
        redisTemplate.opsForGeo().add("home", new Point(115.43,33.1 ), "阿忠女友");
    }

    @GetMapping("/geoDist")
    public String geoDist(){
        Distance m = redisTemplate.opsForGeo().distance("home", "阿忠", "阿忠女友");
        Distance km = redisTemplate.opsForGeo().distance("home", "阿忠", "阿忠女友", RedisGeoCommands.DistanceUnit.KILOMETERS);
        return m.getValue()+":米"+"--"+km.getValue()+":千米";
    }


    @GetMapping("/geoPos")
    public void geoPos(){
        List<Point> position = redisTemplate.opsForGeo().position("home", "阿忠");
        log.info("home :{}",position.toString());
        List<Point> positions = redisTemplate.opsForGeo().position("home", "阿忠", "阿忠女友");
        log.info("home :{}",positions);
    }

    /**
     * 通过经度纬度查找附近的人
     */
    @GetMapping("/search")
    public void search(){
        Circle circle = new Circle(117.485001, 30.647999, Metrics.KILOMETERS.getMultiplier());
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(50);
        GeoResults<RedisGeoCommands.GeoLocation<Object>> byxy = redisTemplate.opsForGeo().radius("home", circle, args);
        log.info("通过经纬度附近的人:{}" + byxy);
    }


    /**
     * 通过地方查找附近5km的2个人
     */
    @GetMapping("/search2")
    public void search2(){
        RedisGeoCommands.GeoRadiusCommandArgs args2 = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(2);
        GeoResults<RedisGeoCommands.GeoLocation<Object>> radius = redisTemplate.opsForGeo().radius("home", "阿忠", new Distance(5, Metrics.KILOMETERS),args2);
        log.info("通过名字附近的人:{}" + radius);
    }



}
